import { isString, trim } from 'lodash';

import { t } from '@/locales';
import { useUserStore } from '@/store';
import { MessagePlugin } from '@/utils/reset-message';

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_API
  // timeout: 3000,
  // withCredentials: true
});
request.defaults.headers.common['Accept-Language'] = 'zh-CN';

request.interceptors.request.use(config => {
  const userStore = useUserStore();
  const { token } = userStore;
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  // refreshToken();

  if (config.data instanceof FormData) {
    config.headers['Content-Type'] = 'multipart/form-data';
    // 剔除参数值前后空格
    config.data.forEach((value, key, parent) => {
      if (isString(parent.get(key))) {
        parent.set(key, trim(value as string));
      }
    });
  } else {
    // 剔除参数值前后空格
    for (const key in config.data) {
      if (Object.prototype.hasOwnProperty.call(config.data, key)) {
        if (isString(config.data[key])) {
          config.data[key] = trim(config.data[key]);
        }
      }
    }
  }
  return config;
});

request.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    let { message } = error;
    if (message === 'Network Error') {
      message = t('public.msg2');
    } else if (message?.includes('timeout')) {
      message = t('public.chunk_err1');
    } else if (message.includes('Request failed with status code')) {
      message = t('public.msg3', {
        path: message.substr(message.length - 3)
      });
    }
    MessagePlugin.error(message, 5000);

    return Promise.reject(message);
  }
);

export default request;
